﻿Imports System.IO
Imports System.Data.Odbc
Imports System.ComponentModel

Public Class Utils

    Public Shared Sub Test()
        'Dim ds As KUeDataLib.KUeDataSerivce = KUeDataLib.ServiceManager.GetInstance().GetKUeDataService()

    End Sub

    Public Shared Function GetTableFromCSV(ByVal path As String) As DataTable
        If Not File.Exists(path) Then
            Throw New FileNotFoundException()
        End If

        Dim fileInfo As New FileInfo(path)
        Dim dataTable As New DataTable()
        Dim connectionString As String = [String].Format("Driver={{Microsoft Text Driver (*.txt; *.csv)}};Dbq={0};", fileInfo.DirectoryName)
        Dim connection As New OdbcConnection(connectionString)
        Dim da As New OdbcDataAdapter([String].Format("select * from [{0}]", fileInfo.Name), connection)
        da.Fill(dataTable)
        Return dataTable
    End Function

    Public Shared Function GetDataTable(ByVal path As String, ByVal seperator As Char) As DataTable
        Dim dt As New DataTable()
        Dim aFile As New FileStream(path, FileMode.Open)
        Using sr As New StreamReader(aFile, System.Text.Encoding.[Default])
            Dim strLine As String = sr.ReadLine()
            Dim strArray As String() = strLine.Split(seperator)

            For Each value As String In strArray
                dt.Columns.Add(value.Trim())
            Next

            Dim dr As DataRow = dt.NewRow()

            While sr.Peek() > -1
                strLine = sr.ReadLine()
                strArray = strLine.Split(seperator)
                dt.Rows.Add(strArray)
            End While
        End Using
        Return dt
    End Function


    Public Shared Function DbNull2Nothing(ByVal value As Object) As Object
        If TypeOf value Is System.DBNull Then
            Return Nothing
        Else
            Return value
        End If
    End Function

    '<System.Runtime.CompilerServices.Extension()> _
    Public Shared Function ToDataTable(Of T)(ByVal data As IList(Of T)) As DataTable
        Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
        Dim table As New DataTable()
        For i As Integer = 0 To props.Count - 1
            Dim prop As PropertyDescriptor = props(i)
            table.Columns.Add(prop.Name, prop.PropertyType)
        Next
        Dim values As Object() = New Object(props.Count - 1) {}
        For Each item As T In data
            For i As Integer = 0 To values.Length - 1
                values(i) = props(i).GetValue(item)
            Next
            table.Rows.Add(values)
        Next
        Return table
    End Function

End Class
